<?php

namespace app\impl;

use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\model\BindDiseasePath;
use app\common\model\DiseasePath;
use app\common\model\DiseasePathBind;
use app\common\model\DiseaseTask;
use app\common\model\PatientInfo;
use app\interfaces\Task;
use app\common\model\PropagandaEducationHistory as PehModel;
use app\common\model\PushMessage as PmModel;
use think\facade\Log;

class SendDiseasePathPlan implements Task
{

    public function run(array $data, string $taskId): ?bool
    {

        $connection = ZhyxMongo::getInstance()->connection;
        $session = $connection->startSession();

        try {
            # 根据患者id获取患者信息
            $patientInfo = (new PatientInfo())->getPatientInfo($data["patientId"]);
            if ($patientInfo) {
                foreach ($data["disease_path"] as $k => $v) {
                    $diseasePath = (new DiseasePath())->getDiseasePathById($v["disease_path_id"]);
                    if (!empty($diseasePath)) {
                        # 判断当前用户是否已经绑定过这个路径，如果绑定过了就不在绑定了
                        $bindCount = (new BindDiseasePath())->where([["patient_id", "=", $data["patientId"]], ["disease_path_id", "=", $v["disease_path_id"]]])->count();
                        if ($bindCount) {
                            continue;
                        }
                        $session->startTransaction(['session' => $session]);
                        # 执行用户与随访路径的绑定
                        $taskInfo = (new DiseasePathBind())->bindDiseasePath($diseasePath, $patientInfo, $data, $session);

                        $session->commitTransaction();
                        # 执行任务的分发
                        //$result = (new \app\common\business\DiseasePath())->pushTask($taskInfo);



                    }
                }
            }
            return true;

        } catch (\Exception $exception) {

            if ($session->getTransactionState() !== "none" && $session->getTransactionState() !== "committed") {
                $session->abortTransaction();
            }
            Log::error("绑定随访记录失败:" . $exception->getMessage() . $exception->getLine() . $exception->getFile());
            return false;
        }
    }
}